<template>
  <div class="home">
    <el-form v-loading="loading"  element-loading-text="视频提交中..."   :model="form" label-width="150px" @submit.prevent="submitForm" ref="ruleFormRef" :rules="rules">
      <el-form-item label="视频文件" prop="video">
        <el-upload
            ref="uploadRef"
            class="upload-demo"
            action="http://192.168.0.47:5001/api/v1/videos/upload"
            :file-list="form.video"
            accept="video/*"
            :auto-upload="true"
            :on-change="handleChange"
            :on-remove="handleRemove"
            multiple
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item label="上传路径" prop="upload_path">
        <el-input v-model="form.upload_path" placeholder="上传路径"></el-input>
      </el-form-item>

      <el-form-item label="采集开始时间" prop="collection_start_time">
        <el-date-picker
            v-model="form.collection_start_time"
            type="datetime"
            placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="采集结束时间" prop="collection_end_time">
        <el-date-picker
            v-model="form.collection_end_time"
            type="datetime"
            placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="泥料材质类型" prop="clay_materials_uuid">
        <el-select
            v-model="form.clay_materials_uuid"
            class="m-2"
            placeholder="请选择"
            size="large"
            style="width: 240px"
        >
          <el-option
              v-for="item in theTypeOfMudMaterial"
              :key="item.id"
              :label="item.name"
              :value="item.uuid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工艺师姓名" prop="craftsman_name">
        <el-input v-model="form.craftsman_name" placeholder="请输入工艺师名称"></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="polt_type_uuid">
        <el-select
            v-model="form.polt_type_uuid"
            class="m-2"
            placeholder="请选择"
            size="large"
            style="width: 240px"
        >
          <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.uuid"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import {ElMessage, FormInstance, FormRules} from 'element-plus';
import * as dayjs from "dayjs";
import {home} from "@/api/home.ts";

const loading = ref(false); // 添加 loading 状态

onMounted(() => {
  getPoltType()
  getTheTypeOfMudMaterial()
})

const ruleFormRef = ref<FormInstance>()
const form = reactive({
  video: [] as any[],
  upload_path: '',
  collection_start_time: '',
  collection_end_time: '',
  clay_materials_uuid: '',
  craftsman_name: '',
  polt_type_uuid: ''
});

const uploadRef = ref();

const handleChange = (file: any, fileList: any[]) => {
  console.log('File changed:', file, fileList);
  form.video = fileList;
};

const handleRemove = (file: any) => {
  form.video = form.video.filter((item: any) => item.uid !== file.uid);
};

const rules = reactive<FormRules>({
  polt_type_uuid: [{required: true, message: '请选择', trigger: 'change',}],
  clay_materials_uuid: [{required: true, message: '请选择', trigger: 'change',}],
  collection_start_time: [
    {
      type: 'date',
      required: true,
      message: '请选择开始时间',
      trigger: 'change',
    },
  ],
  collection_end_time: [
    {
      type: 'date',
      required: true,
      message: '请选择结束时间',
      trigger: 'change',
    },
  ],
  video: [
    {
      type: 'array',
      required: true,
      message: '请上传视频文件',
      trigger: 'change',
    },
  ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (form.video.length === 0) {
        ElMessage.error('请选择一个视频文件');
        return;
      }
      const formData = new FormData();
      form.video.forEach((file) => {
        formData.append('video', file.raw);
      });
      formData.append('upload_path', form.upload_path);
      formData.append('collection_start_time', dayjs(form.collection_start_time).format('YYYY-MM-DD HH:mm:ss'));
      formData.append('collection_end_time', dayjs(form.collection_end_time).format('YYYY-MM-DD HH:mm:ss'));
      formData.append('clay_materials_uuid', form.clay_materials_uuid);
      formData.append('craftsman_name', form.craftsman_name);
      formData.append('polt_type_uuid', form.polt_type_uuid);
      console.log(formData)
      try {
        loading.value = true; // 设置 loading 为 true
        const res = await home.getUploadVideo(formData);
        console.log(res)
        ElMessage.success('视频已提交，等待处理中...');
        // 重置表单数据
        form.video = [];
        form.upload_path = '';
        form.collection_start_time = '';
        form.collection_end_time = '';
        form.clay_materials_uuid = '';
        form.craftsman_name = '';
        form.polt_type_uuid = '';
        uploadRef.value.clearFiles(); // 清空上传文件列表
        // 重置表单校验状态
        formEl.resetFields();
        loading.value = false; // 设置 loading 为 false
      } catch (error) {
        console.error('视频上传失败:', error);
        ElMessage.error('视频上传失败');
      } finally {

      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

interface UserType {
  create_id?: any;
  create_name?: any;
  create_time?: any;
  description?: any;
  enabled: string;
  id: number;
  name: string;
  remark?: any;
  update_id?: any;
  update_name?: any;
  update_time?: any;
  uuid: string;
  valid: string;
  version?: any;
}

const typeList = reactive<UserType[]>([])

const getPoltType = () => {
  loading.value = true; // 设置 loading 为 true
  home.getPoltType().then((res) => {
    console.log(res.data)
    typeList.push(...res.data)
  }).finally(() => {
    loading.value = false; // 设置 loading 为 false
  })
}

const theTypeOfMudMaterial = reactive<UserType[]>([])
const getTheTypeOfMudMaterial = () => {
  loading.value = true; // 设置 loading 为 true
  home.getClay_material().then((res) => {
    console.log(res.data)
    theTypeOfMudMaterial.push(...res.data)
  }).finally(() => {
    loading.value = false; // 设置 loading 为 false
  })
}
</script>

<style scoped>
.home {
  width: 100%;

  margin: 0;
  padding: 30px 50px;
  background-color: white;
  display: flex;
  justify-content: left;
  align-items: flex-start;
}
</style>